package com.jlnk.dagger.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.jlnk.dagger.entity.Course;

import java.util.ArrayList;
import java.util.List;

import jakarta.inject.Inject;

public class CourseDBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "db_course_manager";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME_COURSE = "course";

    @Inject
    public CourseDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        initTable(db);
    }

    private void initTable(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME_COURSE + " (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "course_name TEXT," +
                "teacher TEXT," +
                "classroom TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void insertCourse(Course course) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("course_name", course.getCourseName());
        values.put("teacher", course.getTeacher());
        values.put("classroom", course.getClassroom());
        db.insert(TABLE_NAME_COURSE, null, values);
    }

    public List<Course> selectAllCourse() {
        SQLiteDatabase db = getReadableDatabase();
        List<Course> courseList = new ArrayList<>();
        Cursor cursor = db.query(TABLE_NAME_COURSE,
                null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Course course = new Course();
            course.setId(cursor.getInt(cursor.getColumnIndex("id")));
            course.setCourseName(cursor.getString(cursor.getColumnIndex("course_name")));
            course.setTeacher(cursor.getString(cursor.getColumnIndex("teacher")));
            course.setClassroom(cursor.getString(cursor.getColumnIndex("classroom")));
            courseList.add(course);
        }
        cursor.close();
        return courseList;
    }
}